package com.clei.netty.encoder;

import com.clei.netty.file.dto.MsgBody;
import com.clei.netty.util.TransformUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * MsgBody -> Byte Encoder
 *
 * @author Y
 * @date 2022-04-21
 */
public class MsgToByteEncoder extends MessageToByteEncoder<MsgBody> {

    /**
     * 头
     */
    private final Byte head;

    /**
     * 尾
     */
    private final Byte tail;

    public MsgToByteEncoder(Byte head, Byte tail) {
        this.head = head;
        this.tail = tail;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, MsgBody msg, ByteBuf out) throws Exception {
        byte[] data = msg.toBytes();
        if (null != head && null != tail) {
            data = pack(data);
        }
        out.writeBytes(data);
    }

    /**
     * 包装
     *
     * @param data 原始数据
     * @return 包装后的数据
     */
    private byte[] pack(byte[] data) {
        data = TransformUtil.transform(data);
        byte[] res = new byte[data.length + 2];
        res[0] = this.head;
        res[res.length - 1] = this.tail;
        System.arraycopy(data, 0, res, 1, data.length);
        return res;
    }
}
